package com.zyb.springcloud.controller;

import com.zyb.springcloud.entities.CommonResult;
import com.zyb.springcloud.entities.Payment;
import com.zyb.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@Slf4j
public class PaymentController {

    @Resource
    private PaymentService paymentService;
    @Value("${server.port}")
    private String serverPort;
    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping(value = "/payment/create")
    public CommonResult createPayment(@RequestBody Payment payment) {
        log.debug("enter createPayment ");
        int  result = paymentService.create(payment);
        return result >0 ? new CommonResult(200, "创建成功,serverPort:"+serverPort,payment) :
                new CommonResult(444, "创建失败");
    }


    @GetMapping(value = "/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable Long id) {
        Payment payment = paymentService.getPaymentById(id);
        return payment == null ? new CommonResult<Payment>(444, "没有查到数据") :
                new CommonResult<Payment>(200, "查询成功,serverPort:"+serverPort,payment);
    }

    @GetMapping("/payment/discovery")
    public DiscoveryClient getDiscoveryClient(){
        List<String> serviceList= discoveryClient.getServices();
        for (String elemt:serviceList) {
            log.info("******element******"+elemt);
        }

        List<ServiceInstance> instanceList=discoveryClient.getInstances("cloud-payment-service");

        for (ServiceInstance serviceInstance: instanceList) {
          String instance=serviceInstance.getInstanceId()+"\t"+serviceInstance.getServiceId()+"\t"+serviceInstance.getHost()+"\t"+serviceInstance.getPort()+"\t"+serviceInstance.getScheme()+"\t"+serviceInstance.getMetadata()+"\t"+serviceInstance.getUri();
          log.info("******instance*****"+instance);
        }
        return discoveryClient;
    }

}
